package com.hspedu.furns.web;

import com.hspedu.furns.entity.Furn;
import com.hspedu.furns.entity.Page;
import com.hspedu.furns.service.FurnService;
import com.hspedu.furns.service.impl.FurnServiceImpl;
import com.hspedu.furns.utils.DataUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 徐
 * @version 1.0
 * 处理用户登录首页的数据和分页
 */
public class CustomerFurnServlet extends BasicServlet {
    //定义FurnService属性
    private FurnService furnService = new FurnServiceImpl();

    /**
     * 处理分页和显示数据
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void page(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //进行分页显示
        //获取传入的页码数
        int pageNo = DataUtils.parseInt(request.getParameter("pageNo"),1);
        //获取每页显示数量
        int pageSize = DataUtils.parseInt(request.getParameter("pageSize"), Page.PAGE_SIZE);
        //调用service方法
        Page<Furn> page = furnService.page(pageNo, pageSize);
        //将本页的家居信息放到request域中
        request.setAttribute("page",page);
        //请求转发到首页面
        request.getRequestDispatcher("/views/customer/index.jsp").forward(request,response);
    }

    /**
     * 首页搜索之后，根据名字进行分页显示
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void pageByName(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //进行分页显示
        //获取传入的页码数
        int pageNo = DataUtils.parseInt(request.getParameter("pageNo"),1);
        //获取每页显示数量
        int pageSize = DataUtils.parseInt(request.getParameter("pageSize"), Page.PAGE_SIZE);
        //获取搜索名字
        String name = request.getParameter("name");
        //如果传入参数有name没有带上值，接收到的是""->返回正常家居排序首页
        //如果没有带上name属性，接收到的是null->返回空家居信息首页
        //把这两种情况业务逻辑合并
        if (name == null){
            name = "";
        }
        //调用service方法
        Page<Furn> page = furnService.pageByName(pageNo,pageSize,name);
        //处理分页的超链接,name是否为空都不影响,公共部分
        StringBuilder url = new StringBuilder("customerFurnServlet?action=pageByName");
        if (!name.equals("")){//如果不为"",添加上搜索的名字
            url.append("&name=").append(name);
        }
        page.setUrl(url.toString());
        //将本页的家居信息放到request域中
        request.setAttribute("page",page);
        //请求转发到首页面
        request.getRequestDispatcher("/views/customer/index.jsp").forward(request,response);
    }
}
